package com.athl.netty.netty.ioboundhandler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author hl
 * @Data 2020/9/3
 */
public class MyLongToByteEncoder extends MessageToByteEncoder<Long> {

    /**
     * MessageToByteEncoder 中的 write方法
     *         ByteBuf buf = null;
     *         try {
     *             if (acceptOutboundMessage(msg)) { // 如果是需要处理的类型，进行encoder
     *                 @SuppressWarnings("unchecked")
     *                 I cast = (I) msg;
     *                 buf = allocateBuffer(ctx, cast, preferDirect);
     *                 try {
     *                     encode(ctx, cast, buf);
     *                 } finally {
     *                     ReferenceCountUtil.release(cast);
     *                 }
     *
     *                 if (buf.isReadable()) {
     *                     ctx.write(buf, promise);
     *                 } else {
     *                     buf.release();
     *                     ctx.write(Unpooled.EMPTY_BUFFER, promise);
     *                 }
     *                 buf = null;
     *             } else {    // 如果不是需要处理的类型，跳过
     *                 ctx.write(msg, promise);
     *             }
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
        System.out.println("MyLongToByteEncoder 被调用");
        System.out.println("msg" + msg);
        out.writeLong(msg);
    }
}
